package com.kobe.thread;

/**
 * @author ：caopengfei
 * @date ：2021/5/6
 */
public class SynchronizedABCTest extends Thread{

    private  String value;

    private  Object self;

    private Object prev;

    public SynchronizedABCTest(String value, Object self, Object prev) {
        this.value = value;
        this.self = self;
        this.prev = prev;
    }

    @Override
    public void run() {
        int count = 10;
        while(count > 0 ){
            //先获取上个的对象锁
            synchronized (prev){
                //获取自己的锁
                synchronized (self){
                    System.out.println(value);
                    count--;
                    //唤醒其他等待获得锁的线程
                    self.notifyAll();
                }
                try{
                    //挂起当前现场，并释放锁，等待其他线程唤醒
                    prev.wait();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();

        SynchronizedABCTest synchronizedTestA = new SynchronizedABCTest("A",a,c);
        SynchronizedABCTest synchronizedTestB = new SynchronizedABCTest("B",b,a);
        SynchronizedABCTest synchronizedTestC = new SynchronizedABCTest("C",c,b);

        synchronizedTestA.start();
        Thread.sleep(200L);
        synchronizedTestB.start();
        Thread.sleep(200L);
        synchronizedTestC.start();
        Thread.sleep(200L);
    }




}
